package com.lange.inerceptor;


import com.lange.anno.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
public class LoginInerceptor implements HandlerInterceptor {

    private static final ThreadLocal threadLocal = new ThreadLocal();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       if (handler instanceof HandlerMethod){
           HandlerMethod handlerMethod = (HandlerMethod)handler;
           Log methodAnnotation = handlerMethod.getMethodAnnotation(Log.class);
           if (methodAnnotation != null){
               long start = System.currentTimeMillis();
               threadLocal.set(start);
           }
       }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Log methodAnnotation = handlerMethod.getMethodAnnotation(Log.class);
            if (methodAnnotation != null){
                Method method = handlerMethod.getMethod();
                String requestURI = request.getRequestURI();
                String globalName = method.getDeclaringClass().getName() + "#" + method.getName();
                String desc = methodAnnotation.desc();
                long end = System.currentTimeMillis();
                long start = (long) threadLocal.get();

                long dur = end - start;
                threadLocal.remove();
                log.info("请求路径{}，请求方法{}，描述信息{}，总耗时{}", requestURI,globalName,desc,dur);
            }
        }
    }

}
